package com.yixin.hospital.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.yixin.hospital.common.ApiResult;
import com.yixin.hospital.common.Constant;
import com.yixin.hospital.entity.domain.DrugType;
import com.yixin.hospital.entity.dto.req.drugType.DrugTypeAddReqDTO;
import com.yixin.hospital.entity.dto.req.drugType.DrugTypeEditReqDTO;
import com.yixin.hospital.entity.vo.DrugTypeVO;
import com.yixin.hospital.service.DrugTypeService;
import com.yixin.hospital.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping("/drug-type")
@Api(value = "药品类别管理", tags = "药品类别管理")
public class DrugTypeController {

    @Resource
    DrugTypeService drugTypeService;

    @GetMapping("/list")
    @ApiOperation(value = "药品类别列表（树状）")
    public ApiResult list() {
        List<DrugType> drugTypeList = drugTypeService.list();
        List<DrugTypeVO> deptVOList = BeanUtil.copyToList(drugTypeList, DrugTypeVO.class);
        TreeNodeConfig nodeConfig = new TreeNodeConfig();
        List<Tree<Integer>> treeList = TreeUtil.build(deptVOList, 0, nodeConfig,
                (node, tree) -> {
                    tree.setId(node.getId().intValue());
                    tree.setParentId(node.getPid().intValue());
                    tree.setName(node.getName());
                    tree.putExtra("abb", node.getAbb());
                    tree.putExtra("description", node.getDescription());
                    tree.putExtra("level", node.getLevel());
                    tree.putExtra("sort", node.getSort());
                });
        for (Tree<Integer> integerTree : treeList) {
            getChildren(integerTree);
        }
        treeList.sort(Comparator.comparing(o -> Integer.valueOf((int) o.get("sort"))));
        return ApiResult.success(treeList);
    }

    private List<Tree<Integer>> getChildren(Tree<Integer> integerTree) {
        String abbStr = (String) integerTree.get(("abb"));
        List<String> abbArr = new ArrayList<>();
        for (int i = 0; i < abbStr.length(); i++) {
            abbArr.add(String.valueOf(abbStr.charAt(i)));
        }
        integerTree.put("abb", abbArr);
        if (!CollectionUtil.isEmpty(integerTree.getChildren())) {
            integerTree.getChildren().sort(Comparator.comparing(o -> Integer.valueOf((int) o.get("sort"))));
            for (Tree<Integer> child : integerTree.getChildren()) {
                List<String> childAbbArr = new ArrayList<>();
                childAbbArr.addAll(abbArr);
                childAbbArr.add((String)child.get("abb"));
                child.put("abb", String.join("", childAbbArr));
                getChildren(child);
            }
        }
        return null;
    }

    @PostMapping("/add")
    @ApiOperation(value = "添加药品类别")
    public ApiResult add(@Valid @RequestBody DrugTypeAddReqDTO drugTypeAddReqDTO, HttpServletRequest request) {
        DrugType drugType = new DrugType();
        BeanUtil.copyProperties(drugTypeAddReqDTO, drugType);
        drugType.setPid(drugTypeAddReqDTO.getParentId());
        String userName = JwtUtil.getName(request.getHeader(Constant.AUTHORIZATION));
        drugType.setCreatedBy(userName);
        drugType.setUpdatedBy(userName);
        drugTypeService.save(drugType);
        return ApiResult.success(drugType.getId());
    }

    @PutMapping("/edit")
    @ApiOperation(value = "编辑药品类别")
    public ApiResult edit(@Valid @RequestBody DrugTypeEditReqDTO drugTypeEditReqDTO, HttpServletRequest request) {
        DrugType drugType = new DrugType();
        BeanUtil.copyProperties(drugTypeEditReqDTO, drugType);
        String userName = JwtUtil.getName(request.getHeader(Constant.AUTHORIZATION));
        drugType.setUpdatedBy(userName);
        drugTypeService.updateById(drugType);
        return ApiResult.success();
    }

    @DeleteMapping("/remove/{id}")
    @ApiOperation(value = "删除药品类别")
    public ApiResult remove(@PathVariable int id) {
        drugTypeService.removeById(id);
        return ApiResult.success();
    }
}
